package services;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.axis2.context.MessageContext;

import model.Product;


public class DatabaseService 
{
	private static Statement stmt;
    private static Connection conn;
	
	
	public Boolean consultInventory(Product product)
	{
		String sql = "SELECT productID FROM product WHERE units > 0 AND productID = " + product.getProductId();
		
		try 
		{
            ResultSet rs = getStatement().executeQuery(sql);
            return rs.next();
        }
		catch (SQLException ex) 
		{ ex.printStackTrace(); }
		
		return false;
	}
	
	
	public boolean updateInventory(Product product) 
	{
		String sql = "";
		
		try
		{
			sql = "UPDATE product SET units = units-1 WHERE productID = " + product.getProductId();
			getStatement().execute(sql);
			
			return true;
		}
		catch (SQLException ex)
		{ ex.printStackTrace(); }
		
		return false;
	}
	
	
	private static Statement getStatement()
	{
		if (stmt != null)
			return stmt;
		
		try 
		{
			MessageContext msg = MessageContext.getCurrentMessageContext();
			String url = (String)msg.getParameter("jdbc.url").getValue();
			String user = (String)msg.getParameter("jdbc.user").getValue();
			String password = (String)msg.getParameter("jdbc.pwd").getValue();
							
			// Properties properties = new Properties();
			// FileInputStream input = new FileInputStream("database.properties");
			// properties.load(input);
			// input.close();
									
			// String url = properties.getProperty("jdbc.url");
			// String user = properties.getProperty("jdbc.user");
			// String password = properties.getProperty("jdbc.pwd");
	        
	        Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
		}
		catch (ClassNotFoundException ex) 
		{ System.out.println("Driver JDBC-ODBC n�o encontrado"); }
		catch (SQLException ex) 
		{ System.out.println("Erro: " + ex.getMessage()); } 
		catch (Exception e) 
		{ System.out.println("Erro: " + e.getMessage()); }

        return stmt;
	}
}
